package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.glory.cqaospda.R
import com.glory.cqaospda.adapter.LotListAdapter
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.BatchTrackOutBean
import com.glory.cqaospda.bean.LotInfoBean
import com.glory.cqaospda.bean.MesRejectBean
import com.glory.cqaospda.utils.EditTextEnterUtils
import com.glory.cqaospda.viewmodel.EndRunModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.google.gson.JsonObject
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText
import kotlinx.android.synthetic.main.activity_endrun.*
import kotlinx.android.synthetic.main.activity_title.*

class EndRunActivity:BaseActivity<EndRunModel>() {
    var lotListAdapter: LotListAdapter? = null
    var lotInfoBean:LotInfoBean? = null
    var stepName = ""
    var eqpid = ""
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when(msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@EndRunActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }

    override fun initData() {

        queryEqpData(etEqpId)
        queryLotData(etLotId)
        viewModel.defUI.callObserve.observe(this@EndRunActivity) {
            if (!Constant.okgoError) {
                when (it.type) {
                    1 -> {
                        lotInfoBean = it.item as LotInfoBean
                        stepName = lotInfoBean!!.mStepDesc
                        lotListAdapter!!.setList(lotInfoBean!!.mSubLotList)
                    }
                    2 -> {
                        val batchTrackOutBean = it.item as BatchTrackOutBean
                        viewModel.defUI.toastEvent.value = ToastMessageBean("结束成功", true)
                        if (batchTrackOutBean.lotstate == "" && batchTrackOutBean.lotstepname == ""){
                            intent.setClass(this, HomeActivity::class.java)
                            startActivity(intent)
                            finish()
                        }else {
                            intent.putExtra("type", "BatchTrackOut")
                            intent.putExtra("LotState", batchTrackOutBean.lotstate)
                            intent.putExtra("LotStepName", batchTrackOutBean.lotstepname)
                            val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                            intent.setClass(this@EndRunActivity, clazz)
//                        startActivityForResult(intent,1)
                            startActivity(intent)
                        }
                    }
                    3 ->{
                        val mesRejectData = it.item as MesRejectBean
                        intent.putExtra("type","RejectData")
                        intent.putExtra("mesRejectData",mesRejectData)
                        intent.setClass(this, SkipDialogActivity::class.java)
                        startActivity(intent)
                    }
                }
            }else{
                Constant.okgoError = false
            }
        }
        tvBaseSubmit.setOnClickListener{
            if (Constant.isFastClick()) {
                var pasnum = 0
                if (etLotId.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请扫描LotID", true)
                    return@setOnClickListener
                }
                if (etEqpId.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请扫描设备ID", true)
                    return@setOnClickListener
                }
                if (lotInfoBean == null) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("Lot暂无数据,请检查", true)
                    return@setOnClickListener
                }
                for (num in lotInfoBean!!.mSubLotList) {
                    pasnum += if (num.mSubLotPassNumber == null || num.mSubLotPassNumber.equals("")) 0 else num.mSubLotPassNumber.toInt()
                }
                if (etEqpId.text.toString() == "") {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请扫描设备ID", true)
                } else {
                    val map = JsonObject()
                    map.addProperty("LotNo", etLotId.text.toString())
                    map.addProperty("EquipmentName", etEqpId.text.toString())
                    map.addProperty("StepName", stepName)
                    map.addProperty("InputQty", pasnum.toString())
                    viewModel.defaultBatchTrackOut(map)
                }
            }
        }

        etRemarks.setOnFocusChangeListener(object :View.OnFocusChangeListener{
            override fun onFocusChange(v: View?, vb: Boolean) {
                if (vb){
                    if (etLotId.text.toString() == ""){
                        etLotId.requestFocus()
                    }
                }
            }
        })

        tvTrackIn.setOnClickListener {
            viewModel.defaultGetMesRejectData(etLotId.text.toString(), etEqpId.text.toString())
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        tvTitle.text = "结束批次"
        tvBaseSubmit.text = "确认结束"
        tvTrackIn.text = "查询"
        tvTrackIn.visibility = View.VISIBLE
        stepName = intent.getStringExtra("stepName").toString()

        tvUserName.text = Constant.UserName
        initRecyclerView(rvLotList, this)
        lotListAdapter = LotListAdapter(null)
        rvLotList.adapter = lotListAdapter

        val instance = MyApp.instance
        instance!!.handler = handler
    }

    override fun layoutId(): Int {
        return R.layout.activity_endrun
    }

    private fun queryLotData(
        editText: FreeUI_ClearEditText?
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            if (etEqpId.text.toString().trim { it <= ' ' }.isEmpty()) {
                viewModel.defUI.toastEvent.value = ToastMessageBean("请扫描设备ID", true)
            } else {
                viewModel.defaultLotInfo(s!!, etEqpId.text.toString())
            }
        }
    }

    private fun queryEqpData(
        editText: FreeUI_ClearEditText?
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            etLotId.requestFocus()
        }
    }

    protected fun initRecyclerView(recyclerView: RecyclerView, context: Context?) {
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.itemAnimator = DefaultItemAnimator()
        recyclerView.addItemDecoration(DividerItemDecoration(context, 1))
    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1) {
            when (resultCode) {
                108 -> {
                    finish()
                }
            }
        }
    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == 520) {
            try {
                val view = window.decorView.findFocus() as EditText
                when (view) {
                    etEqpId ->{
                        etEqpId.setText("")
                    }
                    etLotId ->{
                        etLotId.setText("")
                    }
                }
            }catch (e: Exception){
                println(e.message)
            }
        }
        return super.onKeyDown(keyCode, event)
    }
    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            intent.putExtra("type", "KeyEvent")
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivityForResult(intent, 1)
            return false
        }
        return super.onKeyUp(keyCode, event)
    }
}